package com.cgt.xiaotao.promotion.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgt.xiaotao.promotion.constants.PromotionConstants;
import com.cgt.xiaotao.promotion.domain.po.Coupon;
import com.cgt.xiaotao.promotion.domain.po.ExchangeCode;
import com.cgt.xiaotao.promotion.mapper.ExchangeCodeMapper;
import com.cgt.xiaotao.promotion.service.IExchangeCodeService;
import com.cgt.xiaotao.promotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.cgt.xiaotao.promotion.constants.PromotionConstants.COUPON_RANGE_KEY;

@Service
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private final StringRedisTemplate redisTemplate;

    @Override
    @Async("generateExchangeCodeExecutor")//使用自定义线程池中线程
    public void asyncGenerateExchangeCode(Coupon coupon) {
        Integer totalNum = coupon.getTotalNum();//总数量
        //1.生成自增id，借助redis的inrc
        Long increment = redisTemplate.opsForValue().increment(PromotionConstants.COUPON_CODE_SERIAL_KEY, totalNum);
        if (increment == null) {
            return;
        }
        int maxNum = increment.intValue();//自增id最大值
        int begin = maxNum - totalNum + 1;//自增id开始值
        //2.循环调用工具类生成兑换码
        List<ExchangeCode> exchangeCodes = new ArrayList<>();
        for (int i = begin; i <= maxNum; i++) {
            String code = CodeUtil.generateCode(i, coupon.getId());
            CodeUtil.generateCode(i, coupon.getId());
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setId(i);//兑换码id
            exchangeCode.setCode(code);
            exchangeCode.setExchangeTargetId(coupon.getId());//优惠券id
            exchangeCode.setExpiredTime(coupon.getTermEndTime());
            exchangeCodes.add(exchangeCode);
        }
        //3.批量插入数据库
        this.saveBatch(exchangeCodes);


        //写入redis缓存
        redisTemplate.opsForZSet().add(COUPON_RANGE_KEY, coupon.getId().toString(), maxNum);
    }
}